package A_review.review4_21;

import java.util.HashMap;

public class SlidingWindow {
        public String minWindow(String s, String t) {
            HashMap<Character, Integer> need = new HashMap<>();
            for (char a : t.toCharArray()) {
                need.put(a, need.getOrDefault(a,0)+1);
            }
            HashMap<Character, Integer> window = new HashMap<>();
            int left=0,right=0;
            int valid=0;
            int size = s.length();
            int minLen=size+1;
            int start=0;
            while (right<size){
                char c = s.charAt(right);
                right++;
                if (need.containsKey(c)){
                    window.put(c, window.getOrDefault(c,0)+1);
                    if (window.get(c).equals(need.get(c))){
                        valid++;
                    }
                }
                int needSize = need.size();
                while (needSize==valid){
                    c=s.charAt(left);
                    left++;
                    if (need.containsKey(c)){
                        if (window.get(c).equals(need.get(c))){
                       //  CKG TODO 2023/4/21: 我错误写在了这里 就不行 打印出来的结果为ANC   window.put(c,window.get(c)-1);
                            valid--;
                        }
                        //  CKG TODO 2023/4/21: 这句话的顺序很重要
                        window.put(c,window.get(c)-1);
                    }
                    //  CKG TODO 2023/4/21: 这块卡壳了
                    if (valid!=needSize){
                        if (right-left+1<minLen){
                            start=left-1;
                            minLen=right-left+1;
                        }
                    }

                }
            }
            //  CKG TODO 2023/4/21: size+1 还不太理解  就是做个标记 存在有最小的子字符串 这个minLen的数值一定改变
            return  minLen==size+1?"":s.substring(start,start+minLen);
        }

    public int lengthOfLongestSubstring(String s) {
        int res = 0;
        int left = 0, right = 0;
        int length = s.length();
        HashMap<Character, Integer> window = new HashMap<>();

        while (right < length) {
            char c = s.charAt(right);
            window.put(c, window.getOrDefault(c, 0) + 1);
            right++;
//  CKG TODO 2023/4/21: 下面这个for循环保证 left 与 right之间  不会有重复元素
            //  CKG TODO 2023/4/21: 然后下面再比较res 和当前right-left的值之间的大小
            while (window.get(c) > 1) {
                char d = s.charAt(left);
                left++;
                window.put(d, window.get(d) - 1);
            }
            res= Math.max(res,right-left);
        }

        return  res;
    }

    public static void main(String[] args) {
        SlidingWindow slidingWindow = new SlidingWindow();
//        String s = slidingWindow.minWindow("ADOBECODEBANC", "ABC");
        System.out.println(slidingWindow.lengthOfLongestSubstring("abcbc"));
//        System.out.println(s);
    }

}
